#extension GL_EXT_gpu_shader4 : enable
#extension GL_ARB_texture_rectangle : enable 

uniform sampler2DRect unshotVectorsSampler;
uniform sampler2DRect fovVisibilityVectorSampler;

void main(void)
{
	ivec2 textureIndex = ivec2(gl_TexCoord[0].st);
	int receiverIndex = textureIndex.y - 1;
	vec4 unshotVectors = texture2DRect(unshotVectorsSampler, gl_TexCoord[0].st);
	int receivingSurfacesCount = textureSize2DRect(unshotVectorsSampler, 0).y - 1;

	bool isShooterPositionsRow = textureIndex.y == 0;
	if(isShooterPositionsRow)
	{
		for(int i = 0; i < receivingSurfacesCount; ++i)
		{
			if(texture2DRect(unshotVectorsSampler, vec2(gl_TexCoord[0].s, i + 1)).rgb != vec3(0, 0, 0))
			{
				//Write out the center of the shooter face, to reconstruct the shot
				gl_FragData[0] = unshotVectors;
				gl_FragData[1] = unshotVectors;
				return;
			}
		}

		gl_FragData[0] = 0;
		gl_FragData[1] = 0;
	}

	bool isVisible = texture2DRect(fovVisibilityVectorSampler, vec2(receiverIndex, 0));
	bool wasNotVisible = length(texture2DRect(unshotVectorsSampler, vec2(0, receiverIndex))) > 0.5;
	bool isBecomingVisible = isVisible && wasNotVisible;

	if(isBecomingVisible)
	{
		gl_FragData[0] = unshotVectors;
		gl_FragData[1] = vec4(0, 0, 0, 0);
		return;
	}

	gl_FragData[0] = vec4(0, 0, 0, 0);
	gl_FragData[1] = unshotVectors;
}

